import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';
import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
import React, {useEffect, useState} from 'react';
import MainPage from './MainPage';
import CurriculumPage from './CurriculumPage';
import SupervisionPage from './SupervisionPage';
import ZYPage from './ZYPage';
import CheckPage from './CheckPage';
import DoorPage from './DoorPage';
import {navigate, navigationRef} from '../utils/RootNavigation';
import {TopView, Theme} from 'teaset';
import ImageConstants from '../resources/ImageConstants';
import {
  DeviceEventEmitter,
  Dimensions,
  Image,
  ImageBackground,
  Text,
  TouchableNativeFeedback,
  View,
} from 'react-native';
import NewsPage from './NewsPage';
import HttpUtil from 'react-native-cdy-baseui/network/HttpUtil';
import ListPage from 'react-native-cdy-baseui/components/ListPage';
import SettingPage from './SettingPage';
import AsyncStorage from '@react-native-community/async-storage';
import ModalViewUtil from 'react-native-cdy-baseui/utils/ModalViewUtil';
import {responsiveNumber} from 'react-native-responsive-number/src/index';
import ExamPage from './ExamPage';
import moment from 'moment';
const Tab = createBottomTabNavigator();
Theme.set({
  toastPaddingLeft: 20,
  toastPaddingRight: 20,
  toastPaddingTop: 15,
  toastPaddingBottom: 15,
  rowSeparatorColor: '#eee',
  poppMinHeight: 34,
  cbIconSizeLG: 25,
  poppMaxWidth: Dimensions.get('window').width,
  poppMinWidth: Dimensions.get('window').width / 2,
  poppMaxHeight: Dimensions.get('window').height / 2,
  selectIconSizeMD: 80,
  poppItemPaddingBottom: 4,
  poppItemPaddingTop: 4,
  poppItemPaddingLeft: 4,
  poppItemPaddingRight: 4,
  poppAccessoryWidth: 0,
  poppAccessoryPaddingLeft: 0,
  poppItemSeparatorWidth: 0,
  popoverPaddingCorner: 0,
  popoverBorderRadius: 8,
});
ListPage.defaultProps = Object.assign({}, ListPage.defaultProps, {
  pageSizeKey: 'limit',
  pageKey: 'page',
  params: {limit: 20},
  dataKey: '',
  allLoadedText: '',
});
HttpUtil.setResponseDavaValidPraser(
  (data, config) => data.success || data.code === '10000' || data.data,
);
HttpUtil.setResponseDataParser((data, config) => (data ? data.data : null));
HttpUtil.setResponseMessageParser(data => (data ? data.msg : null));
HttpUtil.setResponseDataNeedLogin(
  data => data.code === '99999' || data.code === '10002',
);
function TabComponent() {
  return (
    <Tab.Navigator
      screenOptions={({route}) => ({
        tabBarStyle: {display: 'none'},
        tabBarActiveTintColor: 'tomato',
        tabBarInactiveTintColor: 'gray',
        headerShown: false,
        backgroundColor: 'transparent',
      })}
      backBehavior={'none'}>
      <Tab.Screen
        name="首页"
        component={MainPage}
        options={{
          backgroundColor: 'transparent',
        }}
      />
      <Tab.Screen
        name="新闻"
        component={NewsPage}
        options={{
          backgroundColor: 'transparent',
        }}
      />
      <Tab.Screen
        name="课表"
        component={CurriculumPage}
        options={{
          backgroundColor: 'transparent',
        }}
      />
      <Tab.Screen
        name="占用"
        component={ZYPage}
        options={{
          backgroundColor: 'transparent',
        }}
      />
      <Tab.Screen
        name="门禁"
        component={DoorPage}
        options={{
          backgroundColor: 'transparent',
        }}
      />
    </Tab.Navigator>
  );
}
const Stack = createStackNavigator();
export default () => {
  const [tabIndex, setTabIndex] = useState(0);
  const tabs = [
    ImageConstants.IMG_LEFT_MAIN,
    ImageConstants.IMG_LEFT_CURRICULUM,
    ImageConstants.IMG_LEFT_CURRICULUM,
    ImageConstants.IMG_LEFT_SUPERVISION,
    ImageConstants.IMG_LEFT_CHECK,
  ];
  const tabTitles = ['首页', '新闻', '课表', '占用', '门禁'];
  const [showMenus, setShowMenus] = useState(false);
  const [data, setData] = useState(null);

  useEffect(() => {
    let handler = async () => {
      if (HttpUtil.getItem('ROOM_INFO')) {
        try {
          const result = await HttpUtil.post(
            'stadium/electronicExamModeApi/api/getElectronicClassExamModeListApi',
            {classroomId: HttpUtil.getItem('ROOM_INFO').laboratoryId},
          );
          if (
            result.data &&
            moment().isBetween(
              moment(result.data.examModeStartTime, 'YYYY-MM-DD HH:mm:ss'),
              moment(result.data.examModeEndTime, 'YYYY-MM-DD HH:mm:ss'),
            )
          ) {
            setData(result.data);
            navigate('ExamPage', {data: result.data});
            setShowMenus(false);
          } else {
            if (data) {
              navigate('TabComponent');
            }
            setData(null);
            setShowMenus(true);
          }
        } catch (error) {
          setData(null);
          setShowMenus(true);
        }
      }
    };
    const loadRoomInfo = async () => {
      const roomInfoText = await AsyncStorage.getItem('ROOM_INFO');
      if (roomInfoText && roomInfoText.length > 0) {
        const roomInfo = JSON.parse(roomInfoText);
        HttpUtil.setItem('ROOM_INFO', roomInfo);
        setShowMenus(true);
        handler();
      } else {
        navigate('SettingPage');
        setShowMenus(false);
      }
    };
    loadRoomInfo();
    const event = DeviceEventEmitter.addListener('showMenus', () => {
      setShowMenus(true);
    });

    const event1 = DeviceEventEmitter.addListener('SET_INDEX', index => {
      setTabIndex(index);
    });

    const timer = setInterval(handler, 60 * 1000);

    return () => {
      event.remove();
      event1.remove();
      clearInterval(timer);
    };
  }, []);

  return (
    <TopView style={{flex: 1, width: '100%'}}>
      <NavigationContainer ref={navigationRef}>
        <Stack.Navigator
          screenOptions={{
            backgroundColor: 'transparent',
            headerShown: false,
            tabBarVisible: false,
            presentation: 'modal',
          }}>
          <Stack.Screen
            name="TabComponent"
            options={{
              headerShown: false,
              tabBarVisible: false,
              backgroundColor: 'transparent',
            }}
            component={TabComponent}
          />
          <Stack.Screen
            options={{headerShown: false}}
            name="SettingPage"
            component={SettingPage}
          />
          <Stack.Screen
            options={{headerShown: false}}
            name="ExamPage"
            component={ExamPage}
          />
        </Stack.Navigator>
      </NavigationContainer>
      {showMenus ? (
        <View
          style={{
            flexDirection: 'row',
            position: 'absolute',
            top: '5%',
            left: '15%',
            right: '15%',
            justifyContent: 'space-evenly',
            alignItems: 'center',
          }}>
          {tabs.map((value, index) => {
            const style = {
              paddingTop: 20,
              paddingBottom: 30,
              paddingLeft: 25,
              paddingRight: 25,
              flexDirection: 'row',
              alignItems: 'center',
            };
            if (tabIndex === index) {
              return (
                <ImageBackground
                  source={ImageConstants.IMG_BUTTON_BCG}
                  resizeMode="contain"
                  style={style}>
                  <Image source={value} />
                  <Text
                    style={{fontSize: 30, fontWeight: 'bold', color: '#333'}}>
                    {tabTitles[index]}
                  </Text>
                </ImageBackground>
              );
            } else {
              return (
                <TouchableNativeFeedback
                  onPress={() => {
                    setTabIndex(index);
                    navigate(tabTitles[index]);
                  }}>
                  <View style={style}>
                    <Image source={value} />
                    <Text
                      style={{
                        fontSize: 30,
                        fontWeight: 'bold',
                        color: 'white',
                      }}>
                      {tabTitles[index]}
                    </Text>
                  </View>
                </TouchableNativeFeedback>
              );
            }
          })}
        </View>
      ) : null}
    </TopView>
  );
};
